package com.yiwei.hdb.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yiwei.hdb.R;
import com.yiwei.hdb.api.Api;
import com.yiwei.hdb.api.bean.AddressAddV3Bean;
import com.yiwei.hdb.constant.Const;
import com.yiwei.hdb.constant.UserGlobal;
import com.yiwei.hdb.model.CertificationBasicsModel;
import com.yiwei.hdb.model.DealBeforeV3Model;
import com.yiwei.hdb.util.IdentityStepUtil;
import com.yiwei.hdb.util.Network;
import com.yiwei.hdb.util.RxLifeUtil;
import com.yiwei.hdb.util.ToastUtil;
import com.yiwei.hdb.util.UI;
import com.yiwei.hdb.view.Dialog;
import com.yiwei.hdb.view.FlowViewHorizontal;
import com.yiwei.hdb.view.SelectRelativeV3Dialog;
import com.yiwei.hdb.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import chihane.jdaddressselector.BottomDialog;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

/**
 * Created by Administrator on 2018/6/10.
 */

public class V3AddressIdentityActivity extends BaseActivity implements OnAddressSelectedListener {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_area)
    TextView txtArea;
    @BindView(R.id.edit_address)
    EditText editAddress;
    @BindView(R.id.txt_contact_one)
    TextView txtContactOne;
    @BindView(R.id.txt_relative_one)
    TextView txtRelativeOne;
    @BindView(R.id.txt_contact_two)
    TextView txtContactTwo;
    @BindView(R.id.txt_relative_two)
    TextView txtRelativeTwo;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.step_view)
    FlowViewHorizontal stepView;
    private Unbinder unbinder;
    private int selectRelative = 0;
    private int selectContact = 0;
    private BottomDialog bottomDialog;
    private String province;
    private String city;
    private String area;
    private AddressAddV3Bean.RelativesBean relativesBean1;
    private AddressAddV3Bean.RelativesBean relativesBean2;
    private AddressAddV3Bean.AddressBean addressInfo;
    private List<AddressAddV3Bean.RelativesBean> relativesBeen;
    private SelectRelativeV3Dialog selectRelativeV3Dialog;
    private ArrayList<CertificationBasicsModel.DataBean> oneKeyData;
    private ArrayList<DealBeforeV3Model.DataBean.UplistsBean> SomeKeyData;
    private String isFromOneKey = "-1";
    private IdentityStepUtil stepUtil;
    private String bizType = "contacts";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_identity_v3);
        initBar();
        unbinder = ButterKnife.bind(this);
//        EventBus.getDefault().register(this);
        init();
    }

    private void init() {
        oneKeyData = getIntent().getParcelableArrayListExtra(Const.KEY.ONE_KEY);

        SomeKeyData = getIntent().getParcelableArrayListExtra(Const.KEY.SOME_IDENTITY_KEY);
        txtTitle.setText("基础认证");
        stepUtil = new IdentityStepUtil(this);
        stepUtil.setIdentityData(bizType, txtTitle, stepView, oneKeyData, SomeKeyData);

        bottomDialog = new BottomDialog(this);
        bottomDialog.setOnAddressSelectedListener(this);
        addressInfo = new AddressAddV3Bean.AddressBean();
        addressInfo.name = UserGlobal.getRealName();
        addressInfo.phone = UserGlobal.getMobile();

        relativesBeen = new ArrayList<>();
        relativesBean1 = new AddressAddV3Bean.RelativesBean();
        relativesBean2 = new AddressAddV3Bean.RelativesBean();
        relativesBeen.add(relativesBean1);
        relativesBeen.add(relativesBean2);

        selectRelativeV3Dialog = new SelectRelativeV3Dialog(this).setOnSelect(new SelectRelativeV3Dialog.OnSureListener() {
            @Override
            public void onSure(String name) {
                if (selectRelative == 0) {
                    txtRelativeOne.setText(name);
                } else {
                    txtRelativeTwo.setText(name);
                }
                checkAll();
            }
        });
    }


    private void getSubmitAddress(AddressAddV3Bean.AddressBean addressInfo, List<AddressAddV3Bean.RelativesBean> relativesBeen) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败");
            return;
        }
        AddressAddV3Bean bean = new AddressAddV3Bean();
        bean.address = addressInfo;
        bean.relatives = relativesBeen;
        Api.api_service.getSubmitAddress(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "认证成功");
                    stepUtil.goToNext();
                });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stepUtil = null;
//        EventBus.getDefault().unregister(this);
        unbinder.unbind();
        unbinder = null;
    }

    @Override
    public void onBackPressed() {
        showDialog();
    }

    private void showDialog() {
        Dialog.showV3DefaultDialog(this, "提示", "认证还未完成\n您确定要退出吗？", "取消", "确定", new Dialog.DialogDefaultClickListener() {
            @Override
            public void confirm() {
                finish();
            }

            @Override
            public void cancel() {

            }
        });
    }


    private void checkAll() {
        if (!TextUtils.isEmpty(addressInfo.province) &&
                !TextUtils.isEmpty(UI.toString(editAddress)) &&
                !TextUtils.isEmpty(UI.toString(txtContactOne)) &&
                !TextUtils.isEmpty(UI.toString(txtRelativeOne)) &&
                !TextUtils.isEmpty(UI.toString(txtContactTwo)) &&
                !TextUtils.isEmpty(UI.toString(txtRelativeTwo))) {
            btnSubmit.setSelected(true);
        } else {
            btnSubmit.setSelected(false);
        }
    }

    @OnClick({R.id.btn_submit, R.id.txt_area, R.id.btn_back, R.id.txt_contact_one, R.id.txt_relative_one, R.id.txt_contact_two, R.id.txt_relative_two})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_area:
                bottomDialog.show();
                break;
            case R.id.btn_submit:
                if (TextUtils.isEmpty(addressInfo.province)) {
                    ToastUtil.makeText(this, "请选择所在地区");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(editAddress))) {
                    ToastUtil.makeText(this, "请填写详细地址");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(txtContactOne))) {
                    ToastUtil.makeText(this, "请选择第一个联系人");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(txtRelativeOne))) {
                    ToastUtil.makeText(this, "请选择与联系人关系");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(txtContactTwo))) {
                    ToastUtil.makeText(this, "请选择第二个联系人");
                    return;
                }
                if (TextUtils.isEmpty(UI.toString(txtRelativeTwo))) {
                    ToastUtil.makeText(this, "请选择与联系人关系");
                    return;
                }
                if (UI.toString(txtContactOne).equals(UI.toString(txtContactTwo))) {
                    ToastUtil.makeText(this, "不能选择同一个联系人");
                    return;
                }

                relativesBean1.relationship = UI.toString(txtRelativeOne);
                relativesBean2.relationship = UI.toString(txtRelativeTwo);
                addressInfo.address = UI.toString(editAddress);
                getSubmitAddress(addressInfo, relativesBeen);
                break;
            case R.id.btn_back:
                showDialog();
                break;
            case R.id.txt_contact_one:
                selectContact = 0;

//                Uri uri = Uri.parse("content://contacts/people");
                Uri uri = ContactsContract.Contacts.CONTENT_URI;
                Intent contactIntent = new Intent(Intent.ACTION_PICK, uri);
                checkContactPermission(contactIntent, 300);
                break;
            case R.id.txt_relative_one:
                selectRelative = 0;
                selectRelativeV3Dialog.show();
                break;
            case R.id.txt_contact_two:
                selectContact = 1;
                Uri uri1 = ContactsContract.Contacts.CONTENT_URI;
                Intent contactIntent1 = new Intent(Intent.ACTION_PICK, uri1);
                checkContactPermission(contactIntent1, 300);
                break;
            case R.id.txt_relative_two:
                selectRelative = 1;
                selectRelativeV3Dialog.show();
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 300) {
            if (data == null) {
                return;
            }
            //处理返回的data,获取选择的联系人信息
            Uri uri = data.getData();
            String[] contacts = getPhoneContacts(uri);
            if (contacts == null) {
                ToastUtil.makeText(this, "请开启读取联系人权限", Toast.LENGTH_SHORT);
                return;
            }
            if (TextUtils.isEmpty(contacts[1].replace(" ", ""))) {
                ToastUtil.makeText(this, "联系人电话为空或未开启读取联系人权限", Toast.LENGTH_SHORT);
                return;
            }
//                    去除空格，否者传上去格式有误
// 姓名           txtRelativeTwoContent.setText(contacts[0].replace(" ", ""));
//     手机号       txtRelativeThreeContent.setText(contacts[1].replace(" ", ""));
            if (selectContact == 0) {
                relativesBean1.mobile = contacts[1].replace(" ", "");
                relativesBean1.name = contacts[0].replace(" ", "");

                txtContactOne.setText(contacts[0].replace(" ", "") + contacts[1].replace(" ", ""));
            } else {
                relativesBean2.mobile = contacts[1].replace(" ", "");
                relativesBean2.name = contacts[0].replace(" ", "");

                txtContactTwo.setText(contacts[0].replace(" ", "") + contacts[1].replace(" ", ""));
            }
            checkAll();
        }
    }


    @TargetApi(Build.VERSION_CODES.M)
    private void checkContactPermission(final Intent intent, final int result) {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                startActivityForResult(intent, result);
            }

            @Override
            public void superReject() {

            }

        }, R.string.contact_p, R.string.get_contact, Manifest.permission.WRITE_CONTACTS, Manifest.permission.READ_CONTACTS);
    }

    public String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
//            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }

    @Override
    public void onAddressSelected(Province province, City city, County county, Street street) {
        String s =
                (province == null ? "" : province.name) +
                        (city == null ? "" : city.name) +
                        (county == null ? "" : county.name) +
                        (street == null ? "" : street.name);

        if (province != null) {
            this.province = province.name;
        }
        if (city != null) {
            this.city = city.name;
        }
        if (county != null) {
            if (street != null) {
                area = county.name + street.name;
            } else {
                area = county.name;
            }
        }
        addressInfo.province = this.province;
        addressInfo.city = this.city;
        addressInfo.area = this.area;
        txtArea.setText(s);
        bottomDialog.dismiss();
    }
}
